package com.guaoran.distributed.concurrent.program.demo;

import java.util.concurrent.TimeUnit;

/**
 * @author : guaoran
 * @Description : <br/>
 *  停止线程的两种方式：线程中断，使用volatile + 标志位
 * @date :2019/2/26 11:31
 */
public class ThreadStop {
    private static int i=0;
    private static int j=0;
    private static volatile boolean isStop = false;
    public static void main(String[] args) throws InterruptedException {
        //通过 interrupt 中断线程
        Thread thread = new Thread(()->{
            while(!Thread.currentThread().isInterrupted()){
                i++;
            }
            System.out.println(Thread.currentThread().getName()+i);
        },"通过 interrupt 中断线程");
        thread.start();
        TimeUnit.SECONDS.sleep(1);
        thread.interrupt();

        //通过标志位
        Thread threadFlag = new Thread(()->{
            while(!isStop){
                j++;
            }
            System.out.println(Thread.currentThread().getName()+j);
        },"通过标志位");
        threadFlag.start();
        TimeUnit.SECONDS.sleep(1);
        isStop = true;




    }
}
